import os
from typing import Dict, Any

from .db_helper_1 import MySQLHelper

mirror_conn = None
mirror_params = {
    "host": "101.37.204.55",
    "port": 3306,
    "database": "mirror",
    "user": "mirror",
    "password": "7r2E2RhJhTaBRrZk"
}


def set_mirror_db_conn():
    global mirror_conn, mirror_params
    try:
        mirror_conn = MySQLHelper(mirror_params)
    except Exception as e:
        print(f"源数据库链接失败！%s" % str(e))

    return mirror_conn


def get_mirror_conn():
    global mirror_conn
    return mirror_conn or set_mirror_db_conn()

class Config:
    """系统配置类"""
    
    # RabbitMQ 配置 101.37.204.55
    RABBITMQ_HOST = os.getenv('RABBITMQ_HOST', '127.0.0.1')
    RABBITMQ_PORT = int(os.getenv('RABBITMQ_PORT', 5672))
    RABBITMQ_USERNAME = os.getenv('RABBITMQ_USERNAME', 'guest')
    RABBITMQ_PASSWORD = os.getenv('RABBITMQ_PASSWORD', 'guest')
    RABBITMQ_VHOST = os.getenv('RABBITMQ_VHOST', '/')
    
    # 队列配置
    QUEUES = {
        'task_queue': {
            'durable': True,  # 队列持久化
            'max_priority': 10  # 队列优先级
        }
    }
    
    # 交换器配置
    EXCHANGES = {
        'direct_exchange': {
            'type': 'direct',
            'durable': True
        }
    }
    
    # 绑定配置
    BINDINGS = {
        'task_queue': {
            'exchange': 'direct_exchange',
            'routing_key': 'task'
        }
    }
    
    # 生产者配置
    PRODUCER = {
        'connection_attempts': 5,
        'retry_delay': 2,  # 秒
        'confirm_delivery': True  # 启用发布确认
    }
    
    # 消费者配置
    CONSUMER = {
        'prefetch_count': 1,  # 公平分发
        'reconnect_delay': 5,  # 重连延迟（秒）
        'max_reconnect_attempts': 10  # 最大重连次数
    }
    
    # 日志配置
    LOGGING = {
        'level': 'INFO',
        'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        'file': 'rabbitmq_integration.log'
    }
    
    @classmethod
    def get_rabbitmq_url(cls) -> str:
        """获取 RabbitMQ 连接 URL"""
        return (f'amqp://{cls.RABBITMQ_USERNAME}:{cls.RABBITMQ_PASSWORD}@'
                f'{cls.RABBITMQ_HOST}:{cls.RABBITMQ_PORT}/{cls.RABBITMQ_VHOST}')
    
    @classmethod
    def as_dict(cls) -> Dict[str, Any]:
        """将配置转换为字典"""
        return {attr: getattr(cls, attr) for attr in dir(cls) 
                if not callable(getattr(cls, attr)) and not attr.startswith('__')}    